import { DownOutlined, UpOutlined } from '@ant-design/icons'
import { Checkbox, Form, Typography } from 'antd'
import React, { useEffect } from 'react'
import './index.less'

interface CheckBoxOption {
  label: string
  value: string | number
}
interface CheckBoxData {
  key: string
  label: string
  options: CheckBoxOption[]
}
interface CheckBoxBatchProps {
  data: CheckBoxData[]
  isLoading: boolean
  defaultValue?: Record<string, number[]>
  value?: Record<string, number[]>
  onChange?: (val: Record<string, number[]>) => void
}

const CheckBoxBatch: React.FC<CheckBoxBatchProps> = ({ data = [], isLoading, defaultValue, value, onChange }) => {
  // 非受控内部 state
  const [innerValue, setInnerValue] = React.useState<Record<string, number[]>>(defaultValue || {})
  // 展开/收起状态
  const [expanded, setExpanded] = React.useState(false)

  // 受控同步
  useEffect(() => {
    if (value) {
      setInnerValue(value)
    }
  }, [value])

  // 选项变化
  const handleGroupChange = (key: string, checkedList: number[]) => {
    const newValue = { ...innerValue, [key]: checkedList }
    // 非受控时更新内部 state
    if (value === undefined) {
      setInnerValue(newValue)
    }
    onChange?.(newValue)
  }

  // 根据expanded决定显示的数据
  const displayData = expanded || data.length <= 2 ? data : data.slice(0, 2)

  return (
    <div className="custom_check_box_batch">
      {displayData.map((item) => (
        <Form.Item label={item.label} key={item.key}>
          <Checkbox.Group
            disabled={isLoading}
            options={item.options || []}
            value={innerValue[item.key] || []}
            onChange={(checkedList) => handleGroupChange(item.key, checkedList as number[])}
          />
        </Form.Item>
      ))}
      {/* 展开/收起按钮 */}
      {data.length > 3 && (
        <Typography.Link
          onClick={() => setExpanded((prev) => !prev)}
          className="openorexpand_btn"
          style={{ marginTop: 8 }}
        >
          <span>{expanded ? '收起' : '展开更多筛选项'}</span>
          {expanded ? <UpOutlined /> : <DownOutlined />}
        </Typography.Link>
      )}
    </div>
  )
}

export default CheckBoxBatch
